using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using TickSharp.Core.Interfaces;
using TickSharp.Core.Model;

namespace TickSharp.Core.Infrastructure.Serializers
{
    public class ProjectSerializer : ISerializer<Project>
    {
        private readonly TaskSerializer _taskSerializer;

        public ProjectSerializer(TaskSerializer taskSerializer)
        {
            _taskSerializer = taskSerializer;
        }

        public IEnumerable<Project> Deserialize(XElement elements)
        {
            DateTime parsedDate = DateTime.MinValue;
            return from e in elements.Elements()
                where e.Name.LocalName == "project"
                let hasDate = DateTime.TryParse(e.Element("closed_on").Value, out parsedDate)
                select new Project
                {
                    Id = int.Parse(e.Element("id").Value),
                    Name = e.Element("name").Value,
                    ClientName = e.Element("client_name").Value,
                    Tasks = _taskSerializer.Deserialize(e.Element("tasks")),
                    CreatedAt = DateTime.Parse(e.Element("created_at").Value),
                    UpdatedAt = DateTime.Parse(e.Element("updated_at").Value),
                    OpenedOn = DateTime.Parse(e.Element("opened_on").Value),
                    ClosedOn = hasDate ? (DateTime?)parsedDate : null,
                };
        }
    }
}